package com.xyoto.community.aspect;

import com.xyoto.community.constant.UserLoginStatus;
import com.xyoto.community.enums.WechatLoginEnum;
import com.xyoto.community.exception.ExceptionUtils;
import com.xyoto.community.utils.JwtUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: 廖振辉
 * Date: 2021/11/27
 * Description: 检查登录切面类
 */
@Aspect
@Component
public class RequiresLoginAspect {

    @Autowired
    private HttpServletRequest httpServletRequest;

    /**
     * @author 廖振辉 切入点
     */
    @Pointcut(value = "@annotation(com.xyoto.community.aspect.annotation.RequiresLogin)")
    public void handle() {
    }

    /**
     * 环绕通知，对需要登录的接口进行拦截判断
     * @author 廖振辉
     * @param proceedingJoinPoint
     * @return {@link Object}
     */
    @Around(value = "handle()")
    public Object handleAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        // 判断是否登录，若没登录，则直接返回用户未登录，不执行业务代码
        Integer userId = JwtUtils.getMemberIdByJwtToken(httpServletRequest);
        if (Integer.valueOf(UserLoginStatus.UN_LOGIN).equals(userId)) {
            // 用户未登录
            ExceptionUtils.error(WechatLoginEnum.USER_NOT_LOGIN);
        }
        return proceedingJoinPoint.proceed();
    }

}
